package com.rickpan.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rickpan.dto.request.TeamSettingsRequest;
import com.rickpan.entity.Team;
import com.rickpan.entity.TeamMember;
import com.rickpan.repository.TeamRepository;
import com.rickpan.service.TeamService;
import com.rickpan.service.TeamMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 团队服务实现类
 */
@Service
@Transactional
public class TeamServiceImpl implements TeamService {

    private static final Logger logger = LoggerFactory.getLogger(TeamServiceImpl.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private TeamMemberService teamMemberService;

    @Override
    public Team createTeam(Team team) {
        logger.info("创建团队 name={}, creatorId={}", team.getName(), team.getCreatorId());
        
        // 检查团队名称是否已存在
        if (teamRepository.existsByName(team.getName())) {
            throw new RuntimeException("团队名称已存在: " + team.getName());
        }
        
        // 设置默认状态
        team.setStatus(Team.Status.PENDING);
        team.setCurrentMembers(0); // 初始为0，addMember时会自动更新
        
        // 保存团队
        Team savedTeam = teamRepository.save(team);
        
        // 添加创建者为团队所有者
        TeamMember owner = new TeamMember();
        owner.setTeamId(savedTeam.getId());
        owner.setUserId(team.getCreatorId());
        owner.setRole(TeamMember.Role.OWNER);
        owner.setStatus(TeamMember.Status.ACTIVE);
        
        teamMemberService.addMember(owner);
        
        logger.info("团队创建成功 teamId={}", savedTeam.getId());
        return savedTeam;
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<Team> findById(Long id) {
        return teamRepository.findById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Team> findByCreatorId(Long creatorId) {
        return teamRepository.findByCreatorId(creatorId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Team> findTeamsByUserId(Long userId) {
        logger.info("=== TeamService.findTeamsByUserId ===");
        logger.info("查询用户ID: {}", userId);

        List<Team> teams = teamRepository.findTeamsByUserId(userId);
        logger.info("Repository查询结果数量: {}", teams.size());

        for (Team team : teams) {
            logger.info("找到团队: id={}, name={}, status={}, creatorId={}",
                team.getId(), team.getName(), team.getStatus(), team.getCreatorId());
        }

        logger.info("==============================");
        return teams;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Team> findAll(Pageable pageable) {
        return teamRepository.findAll(pageable);
    }

    @Override
    public Team updateTeam(Team team) {
        logger.info("更新团队信息 teamId={}", team.getId());
        
        Optional<Team> existingTeam = teamRepository.findById(team.getId());
        if (existingTeam.isPresent()) {
            Team existing = existingTeam.get();
            
            // 更新允许修改的字段
            existing.setName(team.getName());
            existing.setDescription(team.getDescription());
            existing.setMaxMembers(team.getMaxMembers());
            existing.setTeamAvatarUrl(team.getTeamAvatarUrl());
            existing.setUpdatedAt(LocalDateTime.now());
            
            return teamRepository.save(existing);
        }
        
        throw new RuntimeException("团队不存在: " + team.getId());
    }

    @Override
    public Team approveTeam(Long teamId) {
        logger.info("审核通过团队 teamId={}", teamId);
        
        Optional<Team> team = teamRepository.findById(teamId);
        if (team.isPresent()) {
            Team existingTeam = team.get();
            
            if (existingTeam.getStatus() != Team.Status.PENDING) {
                throw new RuntimeException("团队状态不是待审核状态");
            }
            
            existingTeam.setStatus(Team.Status.APPROVED);
            existingTeam.setUpdatedAt(LocalDateTime.now());
            
            return teamRepository.save(existingTeam);
        }
        
        throw new RuntimeException("团队不存在: " + teamId);
    }

    @Override
    public Team rejectTeam(Long teamId) {
        logger.info("审核拒绝团队 teamId={}", teamId);

        Optional<Team> team = teamRepository.findById(teamId);
        if (team.isPresent()) {
            Team existingTeam = team.get();

            if (existingTeam.getStatus() != Team.Status.PENDING) {
                throw new RuntimeException("团队状态不是待审核状态");
            }

            existingTeam.setStatus(Team.Status.REJECTED);
            existingTeam.setUpdatedAt(LocalDateTime.now());

            return teamRepository.save(existingTeam);
        }

        throw new RuntimeException("团队不存在: " + teamId);
    }

    @Override
    public void deleteTeam(Long id) {
        logger.info("删除团队 teamId={}", id);

        Optional<Team> team = teamRepository.findById(id);
        if (team.isPresent()) {
            Team existingTeam = team.get();

            // 软删除：设置状态为ARCHIVED
            existingTeam.setStatus(Team.Status.ARCHIVED);
            existingTeam.setUpdatedAt(LocalDateTime.now());

            teamRepository.save(existingTeam);

            // 移除所有团队成员
            List<TeamMember> members = teamMemberService.findByTeamId(id);
            for (TeamMember member : members) {
                member.setStatus(TeamMember.Status.REMOVED);
                teamMemberService.updateMember(member);
            }

            logger.info("团队删除成功 teamId={}", id);
        } else {
            throw new RuntimeException("团队不存在: " + id);
        }
    }

    /**
     * 更新团队成员数量
     */
    public void updateMemberCount(Long teamId) {
        logger.debug("更新团队成员数量 teamId={}", teamId);

        Optional<Team> team = teamRepository.findById(teamId);
        if (team.isPresent()) {
            Team existingTeam = team.get();
            long activeMembers = teamMemberService.countActiveByTeamId(teamId);

            existingTeam.setCurrentMembers((int) activeMembers);
            existingTeam.setUpdatedAt(LocalDateTime.now());

            teamRepository.save(existingTeam);
        }
    }

    /**
     * 检查团队是否已满
     */
    @Transactional(readOnly = true)
    public boolean isTeamFull(Long teamId) {
        Optional<Team> team = teamRepository.findById(teamId);
        if (team.isPresent()) {
            Team existingTeam = team.get();
            return existingTeam.getCurrentMembers() >= existingTeam.getMaxMembers();
        }
        return false;
    }

    /**
     * 统计用户创建的团队数量
     */
    @Transactional(readOnly = true)
    public long countByCreatorId(Long creatorId) {
        return teamRepository.countByCreatorId(creatorId);
    }

    /**
     * 统计用户创建的已批准团队数量
     */
    @Transactional(readOnly = true)
    public long countApprovedByCreatorId(Long creatorId) {
        return teamRepository.countByCreatorIdAndStatus(creatorId, Team.Status.APPROVED);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean isTeamCreator(Long teamId, Long userId) {
        Optional<Team> team = teamRepository.findById(teamId);
        return team.isPresent() && team.get().getCreatorId().equals(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean existsById(Long id) {
        return teamRepository.existsById(id);
    }

    // ==================== 辅助方法 ====================

    /**
     * 获取待审核团队列表（管理员用）
     */
    @Transactional(readOnly = true)
    public List<Team> findPendingTeamsForReview(Pageable pageable) {
        return teamRepository.findPendingTeamsForReview(pageable);
    }

    /**
     * 获取最近创建的团队
     */
    @Transactional(readOnly = true)
    public List<Team> findRecentTeams(Pageable pageable) {
        return teamRepository.findRecentTeams(pageable);
    }

    /**
     * 获取活跃团队列表
     */
    @Transactional(readOnly = true)
    public List<Team> findActiveTeams(Pageable pageable) {
        return teamRepository.findActiveTeams(pageable);
    }

    /**
     * 检查用户是否可以创建团队
     */
    @Transactional(readOnly = true)
    public boolean canCreateTeam(Long userId) {
        // VIP用户可以创建最多5个团队，普通用户不能创建团队
        // 这里简化处理，实际应该检查用户类型
        long teamCount = teamRepository.countByCreatorId(userId);
        return teamCount < 5;
    }

    /**
     * 批量审核团队
     */
    public void batchApproveTeams(List<Long> teamIds) {
        logger.info("批量审核团队 count={}", teamIds.size());

        for (Long teamId : teamIds) {
            try {
                approveTeam(teamId);
            } catch (Exception e) {
                logger.error("批量审核团队失败 teamId={}", teamId, e);
            }
        }
    }

    /**
     * 根据状态查找团队
     */
    @Transactional(readOnly = true)
    public List<Team> findByStatus(Team.Status status) {
        return teamRepository.findByStatus(status);
    }

    /**
     * 分页根据状态查找团队
     */
    @Override
    @Transactional(readOnly = true)
    public Page<Team> findByStatus(Team.Status status, Pageable pageable) {
        return teamRepository.findByStatus(status, pageable);
    }

    /**
     * 获取用户管理的团队
     */
    @Transactional(readOnly = true)
    public List<Team> findManagedTeamsByUserId(Long userId) {
        return teamRepository.findManagedTeamsByUserId(userId);
    }

    /**
     * 搜索团队
     */
    @Transactional(readOnly = true)
    public List<Team> searchTeams(String keyword, Pageable pageable) {
        return teamRepository.searchTeams(keyword, pageable);
    }

    @Override
    public Team getTeamSettings(Long teamId) {
        logger.info("获取团队设置 teamId={}", teamId);

        Optional<Team> teamOpt = teamRepository.findById(teamId);
        if (!teamOpt.isPresent()) {
            throw new RuntimeException("团队不存在: " + teamId);
        }

        return teamOpt.get();
    }

    @Override
    @Transactional
    public Team updateTeamSettings(Long teamId, TeamSettingsRequest request) {
        logger.info("更新团队设置 teamId={}, request={}", teamId, request);

        Optional<Team> teamOpt = teamRepository.findById(teamId);
        if (!teamOpt.isPresent()) {
            throw new RuntimeException("团队不存在: " + teamId);
        }

        Team team = teamOpt.get();

        // 更新基础设置
        team.setVisibility(request.getVisibility());
        team.setJoinMethod(request.getJoinMethod());
        team.setRequireTwoFactor(request.getRequireTwoFactor());
        team.setSessionTimeout(request.getSessionTimeout());

        // 构建JSON设置
        Map<String, Object> settings = new HashMap<>();
        settings.put("defaultPermissions", request.getDefaultPermissions());
        settings.put("enableNotifications", request.getEnableNotifications());
        settings.put("notificationTypes", request.getNotificationTypes());
        settings.put("allowMemberInvite", request.getAllowMemberInvite());
        settings.put("allowMemberCreateProject", request.getAllowMemberCreateProject());
        settings.put("allowMemberManageFiles", request.getAllowMemberManageFiles());

        try {
            String settingsJson = objectMapper.writeValueAsString(settings);
            team.setTeamSettings(settingsJson);
        } catch (JsonProcessingException e) {
            logger.error("序列化团队设置失败: teamId={}, error={}", teamId, e.getMessage());
            throw new RuntimeException("保存团队设置失败: " + e.getMessage());
        }

        team.setUpdatedAt(LocalDateTime.now());
        Team savedTeam = teamRepository.save(team);

        logger.info("团队设置更新成功 teamId={}", teamId);
        return savedTeam;
    }

    @Override
    public boolean isTeamVisibleToUser(Long teamId, Long userId) {
        Optional<Team> teamOpt = teamRepository.findById(teamId);
        if (!teamOpt.isPresent()) {
            return false;
        }

        Team team = teamOpt.get();

        // 检查可见性
        switch (team.getVisibility()) {
            case PUBLIC:
                return true;
            case INTERNAL:
                // 内部可见，需要用户登录（这里假设传入的userId不为null表示已登录）
                return userId != null;
            case PRIVATE:
                // 私有团队，只有成员可见
                return teamMemberService.isTeamMember(teamId, userId);
            default:
                return false;
        }
    }

    @Override
    public Page<Team> findByVisibility(Team.Visibility visibility, Pageable pageable) {
        return teamRepository.findByVisibility(visibility, pageable);
    }
}
